/**
 * portal - jQuery EasyUI
 * 
 * Licensed under the GPL:
 *   http://www.gnu.org/licenses/gpl.txt
 *
 * Copyright 2010 stworthy [ stworthy@gmail.com ] 
 * 
 * Dependencies:
 *   draggable
 *   panel
 * 
 */
(function($){
    /**
	 * initialize the portal
	 */
    function init(target,opts){
        $(target).addClass('portal');
        var table = $('<table border="0" cellspacing="0" cellpadding="0"><tr></tr></table>').appendTo(target);
        var tr = table.find('tr');
		
        var columnWidths = [];
        var totalWidth = 0;
        $(target).children('div:first').addClass('portal-column-left');
        $(target).children('div:last').addClass('portal-column-right');
        $(target).find('>div').each(function(){	// each column panel
            var column = $(this);
            totalWidth += column.outerWidth();
            columnWidths.push(column.outerWidth());
			
            var td = $('<td class="portal-column-td"></td>').appendTo(tr)
            column.addClass('portal-column').appendTo(td);
            column.find('>div').each(function(){	// each portal panel
                var p = $(this).addClass('portal-p').panel({
                    doSize:false,
                    cls:'portal-panel',
                    minimizable:false,
                    onMaximize:function(){
                        $(this).panel("restore");
                        var options = $(this).panel("options");
                        $.createWin({
                            url:options.href,
                            isMax:true,
                            target:target,
                            title:options.title
                        });
                    },
                    tools:opts.tools,
                    onClose:function(){
                        opts.onStateChange.call(target);
                        $(this).panel("destroy");
                    }
                });
                p.panel("header").hover(function(){
                    $(this).find(".panel-tool").fadeIn();
                }, function(){
                    $(this).find(".panel-tool").fadeOut();
                }).find(".panel-tool").hide();
                makeDraggable(target, p);
            });
        });
        for(var i=0; i<columnWidths.length; i++){
            columnWidths[i] /= totalWidth;
        }
		
        $(target).bind('_resize', function(){
            var opts = $.data(target, 'portal').options;
            if (opts.fit == true){
                setSize(target);
            }
            return false;
        });
		
        return columnWidths;
    }
	
    function setSize(target){
        var t = $(target);
        var opts = $.data(target, 'portal').options;
        if (opts.fit){
            var p = t.parent();
            opts.width = p.width();
            opts.height = p.height();
        }
        if (!isNaN(opts.width)){
            if ($.boxModel == true){
                t.width(opts.width - (t.outerWidth() - t.width()));
            } else {
                t.width(opts.width);
            }
        } else {
            t.width('auto');
        }
        if (!isNaN(opts.height)){
            if ($.boxModel == true){
                t.height(opts.height - (t.outerHeight() - t.height()));
            } else {
                t.height(opts.height);
            }
        } else {
            t.height('auto');
        }
		
        var hasScroll = t.find('>table').outerHeight() > t.height();
        var width = t.width();
        var columnWidths = $.data(target, 'portal').columnWidths;
        var leftWidth = 0;
		
        // calculate and set every column size
        for(var i=0; i<columnWidths.length; i++){
            var p = t.find('div.portal-column:eq('+i+')');
            var w = Math.floor(width * columnWidths[i]);
            if (i == columnWidths.length - 1){
                //				w = width - leftWidth - (hasScroll == true ? 28 : 10);
                w = width - leftWidth - (hasScroll == true ? 18 : 0);
            }
            if ($.boxModel == true){
                p.width(w - (p.outerWidth()-p.width()));
            } else {
                p.width(w);
            }
            leftWidth += p.outerWidth();
			
            // resize every panel of the column
            p.find('div.portal-p').panel('resize', {
                width:p.width()
            });
        }
        opts.onResize.call(target, opts.width, opts.height);
    }
	
    /**
	 * set draggable feature for the specified panel
	 */
    function makeDraggable(target, panel){
        var spacer;
        panel.panel('panel').draggable({
            handle:'>div.panel-header>div.panel-title',
            proxy:function(source){
                var p = $('<div class="portal-proxy">proxy</div>').insertAfter(source);
                p.width($(source).width());
                p.height($(source).height());
                p.html($(source).html());
                p.find('div.portal-p').removeClass('portal-p');
                return p;
            },
            onBeforeDrag:function(e){
                e.data.startTop = $(this).position().top + $(target).scrollTop();
            },
            onStartDrag:function(e){
                $(this).hide();
                spacer = $('<div class="portal-spacer"></div>').insertAfter(this);
                setSpacerSize($(this).outerWidth(), $(this).outerHeight());
            },
            onDrag:function(e){
                var p = findPanel(e, this);
                if (p){
                    if (p.pos == 'up'){
                        spacer.insertBefore(p.target);
                    } else {
                        spacer.insertAfter(p.target);
                    }
                    setSpacerSize($(p.target).outerWidth());
                } else {
                    var c = findColumn(e);
                    if (c){
                        if (c.find('div.portal-spacer').length == 0){
                            spacer.appendTo(c);
                            setSize(target);
                            setSpacerSize(c.width());
                        }
                    }
                }
            },
            onStopDrag:function(e){
                $(this).css('position', 'static');
                $(this).show();
                spacer.hide();
                $(this).insertAfter(spacer);
                spacer.remove();
                setSize(target);
				
                var opts = $.data(target, 'portal').options;
                opts.onStateChange.call(target);
            }
        });
		
        /**
		 * find which panel the cursor is over
		 */
        function findPanel(e, source){
            var result = null;
            $(target).find('div.portal-p').each(function(){
                var pal = $(this).panel('panel');
                if (pal[0] != source){
                    var pos = pal.offset();
                    if (e.pageX > pos.left && e.pageX < pos.left + pal.outerWidth()
                        && e.pageY > pos.top && e.pageY < pos.top + pal.outerHeight()){
                        if (e.pageY > pos.top + pal.outerHeight() / 2){
                            result = {
                                target:pal,
                                pos:'down'
                            };
                        } else {
                            result = {
                                target:pal,
                                pos:'up'
                            }
                        }
                    }
                }
            });
            return result;
        }
		
        /**
		 * find which portal column the cursor is over
		 */
        function findColumn(e){
            var result = null;
            $(target).find('div.portal-column').each(function(){
                var pal = $(this);
                var pos = pal.offset();
                if (e.pageX > pos.left && e.pageX < pos.left + pal.outerWidth()){
                    result = pal;
                }
            });
            return result;
        }
		
        /**
		 * set the spacer size
		 */
        function setSpacerSize(width, height){
            if ($.boxModel == true){
                spacer.width(width - (spacer.outerWidth() - spacer.width()));
                if (height){
                    spacer.height(height - (spacer.outerHeight() - spacer.height()));
                }
            } else {
                spacer.width(width);
                if (height){
                    spacer.height(height);
                }
            }
        }
    }
	
	
    $.fn.portal = function(options, param){
        if (typeof options == 'string'){
            return $.fn.portal.methods[options](this, param);
        }
		
        options = options || {};
        return this.each(function(){
            var state = $.data(this, 'portal');
            if (state){
                $.extend(state.options, options);
            } else {
                options = $.extend({}, $.fn.portal.defaults, $.fn.portal.parseOptions(this), options);
                state = $.data(this, 'portal', {
                    options: options,
                    columnWidths: init(this,options)
                });
            }
            if (state.options.border){
                $(this).removeClass('portal-noborder');
            } else {
                $(this).addClass('portal-noborder');
            }
            setSize(this);
        });
    };
	
    $.fn.portal.methods = {
        options: function(jq){
            return $.data(jq[0], 'portal').options;
        },
        resize: function(jq, param){
            return jq.each(function(){
                if (param){
                    var opts = $.data(this, 'portal').options;
                    if (param.width) opts.width = param.width;
                    if (param.height) opts.height = param.height;
                }
                setSize(this);
            });
        },
        getPanels: function(jq, columnIndex){
            var c = jq;	// the panel container
            if (columnIndex >= 0){
                c = jq.find('div.portal-column:eq(' + columnIndex + ')');
            }
            var panels = [];
            c.find('div.portal-p').each(function(){
                panels.push($(this));
            });
            return panels;
        },
        add: function(jq, param){	// param: {panel,columnIndex}
            return jq.each(function(){
                var c = $(this).find('div.portal-column:eq(' + param.columnIndex + ')');
                var p = param.panel.addClass('portal-p');
                p.panel('panel').addClass('portal-panel').appendTo(c);
                makeDraggable(this, p);
                p.panel('resize', {
                    width:c.width()
                });
            });
        },
        remove: function(jq, panel){
            return jq.each(function(){
                var panels = $(this).portal('getPanels');
                for(var i=0; i<panels.length; i++){
                    var p = panels[i];
                    if (p[0] == $(panel)[0]){
                        p.panel('destroy');
                    }
                }
            });
        },
        disableDragging: function(jq, panel){
            panel.panel('panel').draggable('disable');
            return jq;
        },
        enableDragging: function(jq, panel){
            panel.panel('panel').draggable('enable');
            return jq;
        }
    };
	
    $.fn.portal.parseOptions = function(target){
        var t = $(target);
        return {
            width: (parseInt(target.style.width) || undefined),
            height: (parseInt(target.style.height) || undefined),
            border: (t.attr('border') ? t.attr('border') == 'true' : undefined),
            fit: (t.attr('fit') ? t.attr('fit') == 'true' : undefined),
            onStateChange:(t.attr('onStateChange') ? eval(t.attr('onStateChange')) : $.noop())
        };
    };
	
    $.fn.portal.defaults = {
        width:'auto',
        height:'auto',
        border:true,
        tools:[],
        fit:false,
        onResize:function(width,height){},
        onStateChange:function(){}
    };
    $.parser.plugins.push("portal");
})(jQuery);

/**
 * @author GodSon
 * http://www.btboys.com
 * date 2011-5-12 12:30	version 2.1
 * @How to use
 * var path = 'page/newFile.html';
 *	var confing = {
 *		url : path,
 *		title : "标题",
 *		width : 500,
 *		height : 150,
 *		maximizable : false,
 *		buttons : [{
 *				text : '继续>>',
 *				handler : function() {
 *					fun(GETWIN(this));
 *				}
 *		}]
 *	};
 *	var curDialogId = $.createWin(confing);
 *	销毁
 *  $(GETWIN(curDialogId)).destroy();
 */

/**
 * @param {Object} options
 * return windowId
 */
(function ($) {
    /**
     * 创建UUID
     */
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    /**
     * 生成windowId
     */
    function CreateIndentityWindowId() {
        return "UUID-" + (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }
    /**
     * 销毁
     */
    function destroy(target) {
        $(target).dialog("destroy");
    }
		
    /**
     * 获取当前操作的window
     *  @param target 当前窗口的windowId 或者 当前窗口中的元素(element)
     */
    function getWindow(target) {
        if (typeof target == "string") {
            return document.getElementById(target);
        } else {
            return $(target).closest(".window-body");
        }
    }
		
    //入口方法
    //入口方法
    $.createWin = function (options) {
        if (!options.url && !options.contents) {
            $.messager.alert("提示", "缺少必要参数!(url or content)");
            return false;
        }
			
        var windowId = CreateIndentityWindowId();
			
        if (options.winId) {
            windowId = options.winId;
        }else{
            options.winId = windowId;
        }
			
        //如果存在buttons(请看easyui对buttons的定义)，默认添加关闭按钮
        var defaultBtn = [{
            text : '关闭',
            handler : function () {
                $("#" + windowId).dialog("close");
            }
        }
        ];
        $.merge(options.buttons || [], defaultBtn);
			
        options = $.extend({}, $.createWin.defaults, options || {});
			
        if (options.isMax) {
            options.draggable = false;
        }
			
        var dialog = $('<div/>').attr("id", windowId);
			
        if (options.target != 'body') {
            options.inline = true;
        }
        dialog.appendTo($(options.target));
			
        dialog.dialog($.extend({},options,{
            onClose : function () {
                if (typeof options.onClose == "function") {
                    options.onClose.call(dialog);
                }
                destroy(this);
            },
            onMove : function (left, top) {
                if (typeof options.onMove == "function") {
                    options.onMove.call(dialog);
                }
                var o = $.data(this, 'panel').options;
                if (top < 0) {
                    $(this).dialog("move", {
                        "left" : left,
                        "top" : 0
                    });
                } else if (o.maximized) {
                    $(this).dialog("restore");
                    $(this).dialog("move", {
                        "left" : left + 100,
                        "top" : top
                    });
                }
                if (top > ($(o.target).height() - 20)) {
                    $(this).dialog("move", {
                        "left" : left,
                        "top" : ($(o.target).height() - 25)
                    });
                }
            }
        }));
       
			
        if (options.align) {
            var w = dialog.closest(".window");
            switch (options.align) {
                case "right":
                    dialog.dialog("move", {
                        left : w.parent().width() - w.width() - 10
                    });
                    break;
                case "tright":
                    dialog.dialog("move", {
                        left : w.parent().width() - w.width() - 10,
                        top : 0
                    });
                    break;
                case "bright":
                    dialog.dialog("move", {
                        left : w.parent().width() - w.width() - 10,
                        top : w.parent().height() - w.height() - 10
                    });
                    break;
                case "left":
                    dialog.dialog("move", {
                        left : 0
                    });
                    break;
                case "tleft":
                    dialog.dialog("move", {
                        left : 0,
                        top : 0
                    });
                    break;
                case "bleft":
                    dialog.dialog("move", {
                        left : 0,
                        top : w.parent().height() - w.height() - 10
                    });
                    break;
                case "top":
                    dialog.dialog("move", {
                        top : 0
                    });
                    break;
                case "bottom":
                    dialog.dialog("move", {
                        top : w.parent().height() - w.height() - 10
                    });
                    break;
            }
        }
			
        if (options.isMax) {
            dialog.dialog("maximize");
            dialog.dialog("open");
        }
        
        if($.fn.mask &&　options.mask)　dialog.mask();
        	
        if (options.contents) {
            ajaxSuccess(options.contents);
        } else {
            if (!options.isIframe) {
                $.ajax({
                    url : options.url,
                    type : "POST",
                    data : options.data == null ? "" : options.data,
                    success : function (date) {
                        ajaxSuccess(date);
                    },
                    error : function () {
                        $.messager.alert("提示", "加载失败！");
                    }
                });
            } else {
                ajaxSuccess();
            }
        }
        return windowId;
			
        /**
         * 页面加载成功处理
         */
        function ajaxSuccess(date) {
            if (options.isIframe && !date) {
                dialog.find("div.dialog-content").html('<iframe width="100%" height="100%" frameborder="0" src="' + options.url + '" ></iframe>');
            } else {
                dialog.find("div.dialog-content").html(date);
            }
            $.parser.parse(dialog);
            options.onComplete.call(this, windowId);
            if($.fn.mask &&　options.mask) dialog.mask("hide");
        }
    };
		
    //关闭并销毁实体
    $.fn.destroy = function () {
        destroy(this);
    };
		
    window.GETWIN = getWindow;
		
    //默认参数
    $.createWin.defaults = $.extend({}, $.fn.dialog.defaults, {
        url : '', //窗口要加载的html片段地址
        data : '', //可带参数，data类型为jqurey.ajax的data参数类型
        target : 'body', //指定窗口打开的区域,是一个jq的选择器，例如#id
        height : 200,
        width : 400,
        collapsible : false,
        minimizable : false,
        maximizable : false,
        closable : true,
        modal : true,
        shadow : false,
        mask:true,
        onComplete : function (windowId) {}
    //创建成功后的回调方法
    });
})(jQuery);
 
/* 
 *  Document   : mask 1.1
 *  Created on : 2011-12-11, 14:37:38
 *  Author     : GodSon
 *  Email      : wmails@126.com
 *  Link       : www.btboys.com 
 *  
 */
 
(function($){
    function init(target,options){
        var wrap = $(target);
        if($("div.mask",wrap).length) wrap.mask("hide");
		
        wrap.attr("position",wrap.css("position"));
        wrap.attr("overflow",wrap.css("overflow"));
        wrap.css("position", "relative");
        wrap.css("overflow", "hidden");
        
        var maskCss = {
            position:"absolute",
            left:0,
            top:0,
            cursor: "wait",
            background:"#ccc",
            opacity:options.opacity,
            filter:"alpha(opacity="+options.opacity*100+")",
            display:"none"
        };
        
        var maskMsgCss = {
            position:"absolute",
            width:"auto",
            padding:"10px 20px",
            border:"2px solid #ccc",
            color:"white",
            cursor: "wait",
            display:"none",
            borderRadius:5,
            background:"black",
            opacity:0.6,
            filter:"alpha(opacity=60)"
        };
        var width,height,left,top;
        if(target == 'body'){
            width = Math.max(document.documentElement.clientWidth, document.body.clientWidth);
            height = Math.max(document.documentElement.clientHeight, document.body.clientHeight);
        }else{
            width = wrap.outerWidth() || "100%";
            height = wrap.outerHeight() || "100%";
        }
        $('<div class="mask"></div>').css($.extend({},maskCss,{
            display : 'block',
            width : width,
            height : height,
            zIndex:options.zIndex
        })).appendTo(wrap);

        var maskm= $('<div class="mask-msg"></div>').html(options.maskMsg).appendTo(wrap).css(maskMsgCss);
		
        if(target == 'body'){
            left = (Math.max(document.documentElement.clientWidth,document.body.clientWidth) - $('div.mask-msg', wrap).outerWidth())/ 2;
            if(document.documentElement.clientHeight > document.body.clientHeight){
                top = (Math.max(document.documentElement.clientHeight,document.body.clientHeight)  - $('div.mask-msg', wrap).outerHeight())/ 2;
            }else{
                top = (Math.min(document.documentElement.clientHeight,document.body.clientHeight)  - $('div.mask-msg', wrap).outerHeight())/ 2;
            }
			
        }else{
            left = (wrap.width() - $('div.mask-msg', wrap).outerWidth())/ 2;
            top = (wrap.height() - $('div.mask-msg', wrap).outerHeight())/ 2;
        }
		
        maskm.css({
            display : 'block',
            zIndex:options.zIndex+1,
            left : left,
            top :  top
        });
        
        setTimeout(function(){
            wrap.mask("hide");
        }, options.timeout);
            
        return wrap;
    }
       
    $.fn.mask = function(options){   
        if (typeof options == 'string'){
            return $.fn.mask.methods[options](this);
        }
        options = $.extend({}, $.fn.mask.defaults,options);
        return init(this,options);
    };
    $.mask = function(options){  
        if (typeof options == 'string'){
            return $.fn.mask.methods[options]("body");
        }
        options = $.extend({}, $.fn.mask.defaults,options);
        return init("body",options);
    };
	
    $.mask.hide = function(){
        $("body").mask("hide");
    };
	
    $.fn.mask.methods = {
        hide : function(jq) {
            return jq.each(function() {
                var wrap = $(this);
                $("div.mask",wrap).fadeOut(function(){
                    $(this).remove();
                });
                $("div.mask-msg",wrap).fadeOut(function(){
                    $(this).remove();
                    wrap.css("position",  wrap.attr("position"));
                    wrap.css("overflow", wrap.attr("overflow"));
                });
            });
        }
    };
    
    $.fn.mask.defaults = {
        maskMsg:'\u52a0\u8f7d……',
        zIndex:100000,
        timeout:30000,
        opacity:0.6
    };
})(jQuery);

(function($){
    function init(target){
        var opt = $.data(target,"options");
        if(opt.url){
            $.getJSON(opt.url,{},function(resp){
                wrapWithData(target,resp);
            });
        }else{
            wrapWithHtml(target);
        }
    }
    
    function wrapWithHtml(target){
        var opt = $.data(target,"options");
        target = $(target);
        target.addClass("tabs");
        var items = target.children("li");
        $.each(items, function(index,li){
            var data = {
                text:($(li).text()||"无标题"),
                iconCls:($(li).attr("iconCls")||undefined),
                href:($(li).attr("href")||undefined),
                selected:($(li).attr("selected")||false)
            };
            var item = $(li).attr("id", "tab-"+index);
            
            if(data.selected) item.addClass("tabs-selected");
            
            var a = $("<a/>").addClass("tabs-inner").attr("href", "javascript:void(0)");
            var text = $("<span/>").addClass("tabs-title").text(data.text);
            text.appendTo(a);
            
            
            item.click(function(){
                target.find(".tabs-selected").removeClass("tabs-selected");
                $(this).addClass("tabs-selected");
                opt.onClick.call(this,data,index);
            });
            if (data.iconCls) {
                a.append('<span class="tabs-icon '+data.iconCls+'"></span>');
                text.addClass("tabs-with-icon");
            }
            item.html(a);
        })
    }
    
    function wrapWithData(target,data){
        var opt = $.data(target,"options");
        target = $(target).empty();
        target.addClass("tabs");
        $.each(data,function(index){
            var data = this;
            var item = $("<li/>").attr("id", "tab-"+index);
            
            if(data.selected) item.addClass("tabs-selected");
            
            var a = $("<a/>").addClass("tabs-inner").attr("href", "javascript:void(0)");
            var text = $("<span/>").addClass("tabs-title").text(data.text).appendTo(a);
            
            item.click(function(){
                target.find(".tabs-selected").removeClass("tabs-selected");
                $(this).addClass("tabs-selected");
                opt.onClick.call(this,data,index);
            });
            if (data.iconCls) {
                item.append('<span class="tabs-icon '+data.iconCls+'"></span>');
                text.addClass("tabs-with-icon");
            }
        });
    }
    
    $.fn.tab = function(options){   
        if (typeof options == 'string'){
            return $.fn.tab.methods[options](this);
        }
        options = $.extend({}, $.fn.tab.defaults,options);
        $.data(this,"options",options);
        return init(this);
    };
    
    $.fn.tab.methods = {
        hide : function(jq) {
            return jq.each(function() {
                });
        }
    };
    
    $.fn.tab.defaults = {
        url:"",
        onClick:function(data,index){}
    };
    $.parser.plugins.push("tab");
})(jQuery);